//
//  KYPrizeDrawView.m
//  KYCheckInSDK
//
//  Created by 罗新 on 2017/10/31.
//  Copyright © 2017年 KuaiYan  Co.,LTD. All rights reserved.
//

#import "KYPrizeDrawView.h"
#import "KYPrizeDrawCellView.h"
#import "KYCheckInOverallDataModel.h"
#import "KYCheckInPrizeModel.h"
#import "KYCustomCheckInShowView.h"
#import "KYHdMsgBox.h"
#import "KYCacheManager.h"
@interface KYPrizeDrawView()
@property (nonatomic, weak) UIView *bgView;
@property (nonatomic, weak) KYPrizeDrawCellView *prizeView1;
@property (nonatomic, weak) KYPrizeDrawCellView *prizeView2;
@property (nonatomic, weak) KYPrizeDrawCellView *prizeView3;
@property (nonatomic, weak) KYPrizeDrawCellView *prizeView4;
@property (nonatomic, weak) KYPrizeDrawCellView *prizeView5;
@property (nonatomic, weak) KYPrizeDrawCellView *prizeView6;
@property (nonatomic, weak) KYPrizeDrawCellView *prizeView7;
@property (nonatomic, weak) KYPrizeDrawCellView *prizeView8;
@property (nonatomic, weak) UIButton *startButton;
@property (nonatomic, strong) NSArray *cellArr;
/*** 当前所在的cell **/
@property (nonatomic, weak) KYPrizeDrawCellView *currentView;
/*** 变换时间差（用来表示速度） **/
@property (nonatomic, assign) CGFloat intervalTime;
/*** 减速度 **/
@property (nonatomic, assign) CGFloat accelerate;
/*** 减速共耗时间 **/
@property (nonatomic, assign) CGFloat endTimerTotal;
/*** 定时器 **/
@property (nonatomic, strong) NSTimer *timer;
/*** 定时器 **/
@property (nonatomic, strong) NSTimer *prizeTimer;
/***   **/
@property (nonatomic, assign) NSInteger a;

/*** 抽奖次数 **/
@property (nonatomic, assign) NSInteger drawNumber;
/*** 已抽奖次数 **/
@property (nonatomic, assign) NSInteger hasDrawNumber;
/*** 中奖顺序**/
@property (nonatomic, copy) NSArray *drawSortArr;
@end
@implementation KYPrizeDrawView
- (instancetype)init{
    self = [super init];
    if (self) {
        [self setUpSubViews];
    }
    return self;
}

- (void)setUpSubViews{
    self.frame = CGRectMake(0, 0, kScreenWidth, 270);
    self.a = 0;
    self.hasDrawNumber = 0;
    //定义边距
    CGFloat margin = (kScreenWidth - 80*4)/5.;
    CGFloat cellWH = 80;
    KYPrizeDrawCellView *prizeDraw1 = [[KYPrizeDrawCellView alloc] initWithFrame:CGRectMake(margin, margin, cellWH, cellWH)];
    [self addSubview:prizeDraw1];
    self.prizeView1 = prizeDraw1;
    
    KYPrizeDrawCellView *prizeDraw2 = [[KYPrizeDrawCellView alloc] initWithFrame:CGRectMake(margin + (margin +cellWH), margin, cellWH, cellWH)];
    [self addSubview:prizeDraw2];
    self.prizeView2 = prizeDraw2;
    
    KYPrizeDrawCellView *prizeDraw3 = [[KYPrizeDrawCellView alloc] initWithFrame:CGRectMake(margin + 2 * (margin +cellWH), margin, cellWH, cellWH)];
    [self addSubview:prizeDraw3];
    self.prizeView3 = prizeDraw3;
    
    KYPrizeDrawCellView *prizeDraw4 = [[KYPrizeDrawCellView alloc] initWithFrame:CGRectMake(margin + 3 * (margin +cellWH), margin, cellWH, cellWH)];
    [self addSubview:prizeDraw4];
    self.prizeView4 = prizeDraw4;
    
    KYPrizeDrawCellView *prizeDraw5 = [[KYPrizeDrawCellView alloc] initWithFrame:CGRectMake(margin + 3 * (margin + cellWH), margin + (margin + cellWH), cellWH, cellWH)];
    [self addSubview:prizeDraw5];
    self.prizeView5 = prizeDraw5;
    
    KYPrizeDrawCellView *prizeDraw6 = [[KYPrizeDrawCellView alloc] initWithFrame:CGRectMake(margin + 2 * (margin + cellWH), margin + (margin + cellWH), cellWH, cellWH)];
    [self addSubview:prizeDraw6];
    self.prizeView6 = prizeDraw6;
    
    KYPrizeDrawCellView *prizeDraw7 = [[KYPrizeDrawCellView alloc] initWithFrame:CGRectMake(margin + 1 * (margin + cellWH), margin + (margin + cellWH), cellWH, cellWH)];
    [self addSubview:prizeDraw7];
    self.prizeView7 = prizeDraw7;
    
    KYPrizeDrawCellView *prizeDraw8 = [[KYPrizeDrawCellView alloc] initWithFrame:CGRectMake(margin, margin + (margin + cellWH), cellWH, cellWH)];
    [self addSubview:prizeDraw8];
    self.prizeView8 = prizeDraw8;
    
    //添加抽奖按钮
    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    startButton.frame = CGRectMake((kScreenWidth-220)/2, 220, 220, 35);
    startButton.backgroundColor = [UIColor colorWithRGBHex:0xc3493b];
    [startButton setBackgroundImage:[UIImage ky_imageWithColor:[UIColor colorWithRGBHex:0xc3493b]] forState:UIControlStateNormal];
    [startButton setBackgroundImage:[UIImage ky_imageWithColor:[UIColor colorWithRGBHex:0xd6d6d6]] forState:UIControlStateDisabled];
    startButton.layer.cornerRadius = 15;
    startButton.layer.masksToBounds = YES;
    [startButton setTitle:@"立即抽奖" forState:UIControlStateNormal];
    [startButton addTarget:self action:@selector(prepareLotteryAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:startButton];
    self.startButton = startButton;
    self.startButton.enabled = NO;
    
    self.cellArr = @[prizeDraw1,prizeDraw2,prizeDraw3,prizeDraw4,prizeDraw5,prizeDraw6,prizeDraw7,prizeDraw8];
     NSInteger count = self.cellArr.count;
    //添加tag值
    for (NSInteger i=0; i<count; i++) {
        KYPrizeDrawView *prizeView = self.cellArr[i];
        prizeView.tag = i + 20;
    }
    self.currentView = prizeDraw1;
    self.currentView.layer.borderWidth = 2.0;
}
//抽奖按钮按下后的准备工作
- (void)prepareLotteryAction {
    if (self.drawNumber == 0){
        self.startButton.enabled = NO;
        [[KYHdMsgBox sharedInstance] showAlertText:@"抽奖次数已用完，请明天再试"];
        return;
    }
    self.drawNumber --;
    //更新剩余次数
    [self.delegate updateTheDrawNumberWith:self.drawNumber];
    
    //存储最新的数据
    KYCacheManager *cacheMgr = [KYCacheManager shareInstance];
    NSString *cachekey = [NSString stringWithFormat:@"KYPrize%@",[NSDate currentDayString]];
    if ([cacheMgr ky_isContainObjectForKey:cachekey]) {
        KYCheckInOverallDataModel *model = (KYCheckInOverallDataModel *)[cacheMgr ky_ObjectForKey:cachekey];
        model.retainDrawNumber = self.drawNumber-self.hasDrawNumber;
        [cacheMgr ky_setObject:model forKey:cachekey];
    }
    
    self.intervalTime = 0.4;//起始的变换时间差（速度）
    self.currentView.layer.borderWidth = 0.0;
    //将当前滚到的cell指向第一个
    self.currentView = [self.cellArr objectAtIndex:0];
    self.currentView.layer.borderWidth = 2.0;
    //点击抽奖按钮状态为不可用
    self.startButton.enabled = NO;
    //创建计时器
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.intervalTime target:self selector:@selector(startLotterry:) userInfo:self.currentView repeats:NO];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.prizeTimer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(endLotteryWithResultValue) userInfo:self.currentView repeats:YES];
        self.hasDrawNumber ++;
    });
}
//开始抽奖
-(void)startLotterry:(NSTimer *)sender{
    //将当前的cellView传过来
    NSUInteger count = self.cellArr.count;
    NSTimer *myTimer = (NSTimer *)sender;
    KYPrizeDrawCellView *preView = (KYPrizeDrawCellView *)myTimer.userInfo;
    NSUInteger index;
    //将当前角标传过来
    if (preView==nil) {
        index = 0;
    }else{
        index = [self.cellArr indexOfObject:preView];
    }
    //如果是最后一个
    if (index==count-1) {
        self.currentView = [self.cellArr objectAtIndex:0];
    }else{
        self.currentView = [self.cellArr objectAtIndex:index+1];
    }
    //移动到当前view
    [self moveCurrentView:self.currentView inArray:self.cellArr];
    //开始加速到匀速
    if (self.intervalTime>0.2) {
        self.intervalTime = self.intervalTime - 0.1;
    }
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.intervalTime target:self selector:@selector(startLotterry:) userInfo:self.currentView repeats:NO];
}

//停到某个指定的值
-(void)endLotteryWithResultValue{
    //速度变成0.3后开始减速
//    self.intervalTime=0.3;
//    NSLog(@"tingle %ld",resultValue);
    /*
    //获取当前的view所在的角标
    NSUInteger currentIndex = [self.cellArr indexOfObject:self.currentView];
    //当前数组的个数
    NSUInteger count = self.cellArr.count;
    //距离结尾还剩的长度
    NSUInteger endLength;
    //
    if (currentIndex>resultValue) {
        endLength = count-(currentIndex-resultValue);
    }else{
        endLength = resultValue-currentIndex;
    }
    //    intervalTime = (0.1+0.1*endLength)*endLength/2.0;
    self.endTimerTotal = 3;
    a = (2*self.endTimerTotal/endLength-2*self.intervalTime)/(endLength-1);
    */
//    NSUInteger currentIndex = [self.cellArr indexOfObject:self.currentView];
//    NSUInteger count = self.cellArr.count;
//    //距离目标值的长度
//    NSUInteger endLength;
//    if (currentIndex>resultValue) {
//        endLength = count-(currentIndex-resultValue);
//    }else{
//        endLength = resultValue-currentIndex;
//    }
//    self.endTimerTotal = 2;
//    self.accelerate = (2*self.endTimerTotal/endLength-2*self.intervalTime)/(endLength);
//    [self moveToStopWithAccelerate];
    NSUInteger currentIndex = [self.cellArr indexOfObject:self.currentView];
    KYCheckInPrizeModel *model = self.drawSortArr[self.hasDrawNumber];
    NSInteger index = model.modelIndex.integerValue;
    if (currentIndex == index) {
        [self.timer invalidate];
        self.timer = nil;
        [self.prizeTimer invalidate];
        self.prizeTimer = nil;
        if (model.prizeDatialModel) {
            // 弹出广告
            KYCustomCheckInShowView *showView = [KYCustomCheckInShowView customCheckInShowView];
            [showView refreshDataWithModel:model.prizeDatialModel];
            showView.adViewClick = ^{
                [self.delegate adClickWithModel:model.prizeDatialModel];
            };
            showView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            [showView show];
        }else{
            [[KYHdMsgBox sharedInstance] showAlertText:@"谢谢惠顾~"];
        }
        self.startButton.enabled = YES;
    }
}

//减速效果暂时不做了，计算过程出了点问题，后续再修改
/*
//减速至停止
-(void)moveToStopWithAccelerate{
    static float timeTotal = 0;
    if (self.a<=self.accelerate) {
        self.a++;
        self.intervalTime = 0.3*self.a;
        [self.timer invalidate];
        self.currentView = [self nextViewByCurrentView:self.currentView inArray:self.cellArr];
        [self moveCurrentView:self.currentView inArray:self.cellArr];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:self.intervalTime target:self selector:@selector(moveToStopWithAccelerate) userInfo:nil repeats:NO];
    }
    if (self.a>=self.accelerate) {
        [self.timer invalidate];
        timeTotal = 0;
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"恭喜你！抽中%d个积分",(self.currentView.tag+1)*2] delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        self.startButton.enabled = YES;
        self.intervalTime=0.7;
        self.a=0;
    }
}
*/
//单元格移动一下(从上一个移动到当前view)
-(void)moveCurrentView:(KYPrizeDrawCellView *)curView  inArray:(NSArray *)views{
    KYPrizeDrawCellView *preView = [self previewByCurrentView:curView inArray:views];
    //改背景和文字
    preView.layer.borderWidth = 0.0;
    curView.layer.borderWidth = 2.0;
}

//将数据更新后传入
- (void)refreshPrizeDrawDataWithDataArr:(NSArray *)arrM prizeDrawOverallData:(KYCheckInOverallDataModel *)model{
    for (NSInteger i = 0; i < arrM.count; i ++) {
        KYCheckInPrizeModel *model = arrM[i];
        KYPrizeDrawCellView *cellView = self.cellArr[i];
        [cellView refreshDataWithModel:model];
    }
    if (model.retainDrawNumber>0) {
        self.drawNumber = model.retainDrawNumber;
        self.hasDrawNumber = 0;
        self.startButton.enabled = YES;
    }
    self.drawSortArr = [arrM sortedArrayUsingComparator:^NSComparisonResult(KYCheckInPrizeModel *  _Nonnull obj1, KYCheckInPrizeModel *  _Nonnull obj2) {
        //给对象排序
        NSComparisonResult result = [obj1 compareParkInfo:obj2];
        return result;
    }];
}
//得到上一个view
-(KYPrizeDrawCellView *)previewByCurrentView:(KYPrizeDrawCellView *)curView inArray:(NSArray *)views{
    NSUInteger count = views.count;
    //获取当前角标
    NSUInteger curIndex = [views indexOfObject:curView];
    //置空上个角标
    NSUInteger preIndex;
    //如果当前角标为0
    if (curIndex==0) {
        preIndex = count-1;
    }else{
        preIndex = curIndex-1;
    }
    //返回上一个view
    return [views objectAtIndex:preIndex];
}

//根据当前view 得到下一个view
-(KYPrizeDrawCellView *)nextViewByCurrentView:(KYPrizeDrawCellView *)curView inArray:(NSArray *)views{
    NSUInteger count = views.count;
    NSUInteger curIndex = [views indexOfObject:curView];
    NSUInteger nextIndex;
    if (curIndex==count-1) {
        nextIndex = 0;
    }else{
        nextIndex = curIndex+1;
    }
    return [views objectAtIndex:nextIndex];
}

@end
